import { Component, ChangeDetectorRef, ChangeDetectionStrategy, Input } from '@angular/core';
import { CompanyRiskRatingService } from '../../companyRiskRating.service';
import { AnalystViewModel } from '../../templates/analystView/analystView.model';
import { HttpClient } from '@angular/common/http';
import { Subscription } from 'rxjs/Subscription';
import { ClusterModelWrapper } from '../../../../riskCluster/cluster.model';
import * as _ from 'lodash';
import { ClusterService } from '../../../../riskCluster/cluster.service';

declare var Modernizr: any;
declare var $: any;

/**
 * Company analyst view summary component
 *
 * Author: Sorin Spiru
 * Date: 16.01.2018
 */
@Component({
    selector: 'summary-analyst-view',
    templateUrl: '../../templates/analystView/analystView.component.html',
    styleUrls: [
        '../../../company.component.scss',
        '../../companyRiskRating.component.scss',
        '../../templates/analystView/analystView.component.scss'
    ],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class AnalystViewSummaryComponent extends AnalystViewModel {
    public currentClusterName: string;
    public riskClusters: ClusterModelWrapper[];
    public exposure: number;
    public management: number;
    public manageableRisk: number;
    public managedRisk: number;
    public managementCode: string;
    public exposureCode: string;
    public meiIsMain: boolean;
    public exposureAssesment: string;
    public managementAssesment: string;
    public intervalExposurechartColors: string[];
    public intervalManagementchartColors: string[];
    public finalBetaFactor: string;
    public subindustryExposureScore: number;
    public overallBetaFactor: string;

    @Input() displayType = 'distribution';
    @Input() isCore = false;

    constructor(
        private cdRef: ChangeDetectorRef,
        private riskService: CompanyRiskRatingService,
        private clusterService: ClusterService) {
        super(cdRef);
        this.isMei = false;
        this.intervalExposurechartColors = ['#CCCCCC', '#F9DE94', '#F6CD5C'];
        this.intervalManagementchartColors = ['#CCCCCC', '#E6F5F5', '#7CD0CE'];
    }

    ngOnInit() {
        this.loaded = new Promise<void>((resolve, reject) => {
            this.riskService.company.subscribe(company => {
                if (!this.isCore) {
                    this.riskService.getCompanySubIndustryExposure(company.id).subscribe(exposureData => {
                        const current = exposureData.find(exposure => exposure.companyId === company.id);
                        this.exposure = current.exposure;
                        this.management = current.management;
                        this.manageableRisk = current['manageableRisk'] || 0;
                        this.managedRisk = current['managedRisk'] || 0;
                        this.overallBetaFactor = company['overallBetaFactor'] ? company['overallBetaFactor'].toFixed(2) : 'N/A';
                        this.subindustryExposureScore = company['subIndustryExposureScore'];

                        this.cdRef.markForCheck();

                        // exposure clusters
                        this.setExposureClusters();

                        // management clusters
                        this.setManagementClusters();
                    });

                    this.overallExposureAssessment = company.comments.overallExposureAssessment;
                    this.exposureComment = (company.comments.exposure ? company.comments.exposure : "") + (this.overallExposureAssessment != null ? (this.overallExposureAssessment) : "");

                    this.overallManagementAssessment = company.comments.overallManagementAssessment;
                    this.esgRiskManagement = (company.comments.esgRiskManagement ? company.comments.esgRiskManagement : "") + (this.overallManagementAssessment != null ? (this.overallManagementAssessment) : "");

                } else {
                    this.exposure = company.exposure['value'];
                    this.exposureComment = this.getCompanySentences(company, [2]);
                    this.esgRiskManagement = this.getCompanySentences(company, [3, 4, 5]);
                    this.management = company['managementRisk'];
                    this.managedRisk = company['managedRisk'] || 0;
                    this.manageableRisk = company['manageableRisk'] || 0;
                    this.finalBetaFactor = company['finalBetaFactor'].toFixed(2);
                    this.subindustryExposureScore = company['subIndustryExposureScore'];

                    // exposure clusters
                    this.setExposureClusters();

                    // management clusters
                    this.setManagementClusters();
                }

                this.cdRef.markForCheck();
                resolve();
            });
        });
    }

    get maxExposure() {
        return 100;
    }

    get maxManagement() {
        return 100;
    }

    private setExposureClusters() {
        this.clusterService.getSummaryExposureRiskClusters().subscribe(clusters => {
            this.exposureClusters = clusters;
            this.exposureClusters.forEach((cluster, index) => {
                if (!this.exposureCode && this.exposure <= cluster.topInterval) {
                    this.exposureCode = index.toString();
                    this.exposureAssesment = cluster.shortName || cluster.name;
                }
            });
            this.cdRef.markForCheck();
        });
    }

    private setManagementClusters() {
        this.clusterService.getSummaryManagementRiskClusters().subscribe(clusters => {
            this.managementClusters = clusters;
            this.managementClusters.forEach((cluster, index) => {
                if (this.management <= cluster.topInterval) {
                    this.managementCode = index.toString();
                    this.managementAssesment = cluster.shortName || cluster.name;
                }
            });
            this.cdRef.markForCheck();
        });
    }

    private getCompanySentences(company, indexes = []) {
        const sentences: Array<any> = _.chain(company['sentences'])
            .pick(indexes)
            .mapValues('value')
            .values()
            .value();
        return sentences.join(' ');
    }
}